package shuangzu.top.zzurla.activities;

import android.Manifest;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.maps2d.model.PolygonOptions;
import com.spark.submitbutton.SubmitButton;
import easypermission.davidinchina.com.easylibrary.EasyPermission;
import easypermission.davidinchina.com.easylibrary.util.EasyPermissionUtil;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import shuangzu.top.zzurla.R;
import shuangzu.top.zzurla.utils.utils_date;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

import static cn.pedant.SweetAlert.SweetAlertDialog.*;

public class checkio_activity extends Activity implements AMapLocationListener, LocationSource {

    private TextView locinfo;
    private MapView mapView;
    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private double location_longitude=0;  //记录的精度
    private double location_latitude=0;  //记录的维度
    //private Button button_checkin;
    private SubmitButton button_checkin;
    SweetAlertDialog pDialog;
    private Handler hander=null;
    private String errorinfo="";
    private boolean locationFlag=false;
    private utils_date ud;
    private SharedPreferences pref;



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.checkio_activity);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        locinfo=(TextView)findViewById(R.id.locationinfo);
        LinearLayout mapqd_window=(LinearLayout)findViewById(R.id.mapqd_window);
        mapqd_window.bringToFront();
        button_checkin=(SubmitButton) findViewById(R.id.mapqd_button_checkin);
        pDialog = new SweetAlertDialog(this, PROGRESS_TYPE);
        hander=new Handler();
        pref= PreferenceManager.getDefaultSharedPreferences(this);
        ud=new utils_date();
        button_checkin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pDialog = new SweetAlertDialog(checkio_activity.this, PROGRESS_TYPE);
                pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                pDialog.setTitleText("正在上传数据....");
                pDialog.setCancelable(false);
                pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        pDialog.dismissWithAnimation();
                    }
                });
                pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        pDialog.cancel();
                    }
                });
                pDialog.show();
                new Thread() {
                    public void run() {
                        try {

                            //locationFlag=true;
                            //此处写校验地理位置和代码
                            if(locationFlag)
                            {
                                //说明处于实验室地理位置
                                try{
                                    //上传签到数据
                                    OkHttpClient client =new OkHttpClient();
                                    String loc=location_longitude + "," + location_latitude;
                                    String user_id=pref.getString("username","default");
                                    FormBody formbody=new FormBody
                                            .Builder()
                                            .add("user_id",user_id)
                                            .add("check_type","1")
                                            .add("check_time",ud.getnow_national())
                                            .add("check_loc", loc)
                                            .build();
                                    Request request=new Request.Builder()
                                            .url("http://server.aspi.tech:8080/zrla/check/save")
                                            .post(formbody)
                                            .build();
                                    Response response=client.newCall(request).execute();
                                    String responseData=response.body().string();
                                    if(responseData.equals("SUCCESS"))
                                    {
                                        //说明签到成功
                                        hander.post(ui_uploaddata_success);
                                    }
                                    else
                                    {
                                        //hander.post(ui_uploaddata_faild);
                                        errorinfo=responseData;
                                        hander.post(ui_info);
                                    }
                                }catch (Exception e)
                                {
                                    e.printStackTrace();

                                    hander.post(ui_uploaddata_faild);
                                }
                            }
                            else{
                                //说明不处于实验室地理位置
                                hander.post(ui_uploaddata_faild);
                            }

                        } catch (
                                Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
        init();

    }

    Runnable ui_uploaddata_success=new Runnable() {
        @Override
        public void run() {
            pDialog.changeAlertType(SUCCESS_TYPE);
            pDialog.setTitleText("签到成功");
            pDialog.setCancelable(true);
            pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    pDialog.dismissWithAnimation();
                }
            });
            pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    pDialog.cancel();
                }
            });
            pDialog.show();
        }
    };
    Runnable ui_uploaddata_faild=new Runnable() {
        @Override
        public void run() {
            pDialog.changeAlertType(ERROR_TYPE);
            if(locationFlag)
            {
                pDialog.setTitleText(ud.getnow_national() + "网络错误，无法上传数据！");
            }
            else
            {
                pDialog.setTitleText("您不处于实验室范围！请在实验室附近退出重试！");
            }
            pDialog.setCancelable(true);
            pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    pDialog.dismissWithAnimation();
                }
            });
            pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    pDialog.cancel();
                }
            });
            pDialog.show();

        }
    };
    Runnable ui_info=new Runnable() {
        @Override
        public void run() {
            pDialog.changeAlertType(ERROR_TYPE);
            pDialog.setTitleText(errorinfo);
            pDialog.setCancelable(true);
            pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    pDialog.dismissWithAnimation();
                }
            });
            pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    pDialog.cancel();
                }
            });
            pDialog.show();
        }
    };



    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    private void setUpMap() {
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        //myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色

        myLocationStyle.radiusFillColor(Color.argb(100, 0, 180, 0));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.moveCamera(CameraUpdateFactory.zoomTo(19));
        // aMap.setMyLocationType()

        //绘制多边形，必须在这个多边形内签到！
        LatLng latLng1 = new LatLng(34.812177, 113.537504);
        LatLng latLng2 = new LatLng(34.81216, 113.538373);
        LatLng latLng3 = new LatLng(34.811842, 113.538373);
        LatLng latLng4 = new LatLng(34.811794, 113.537617);
        LatLng latLng5 = new LatLng(34.81201, 113.537247);

        // 声明 多边形参数对象
        PolygonOptions polygonOptions = new PolygonOptions();
        // 添加 多边形的每个顶点（顺序添加）
        polygonOptions.add(latLng1, latLng2, latLng3, latLng4, latLng5);
        polygonOptions.strokeWidth(15) // 多边形的边框
                .strokeColor(Color.argb(30, 0, 0, 240)) // 边框颜色
                .fillColor(Color.argb(30, 0, 0, 240));   // 多边形的填充色
        aMap.addPolygon(polygonOptions);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                String tlt="";
                tlt=aMapLocation.getAddress() + "\n" + aMapLocation.getGpsAccuracyStatus() + "\n维度：" + aMapLocation.getLatitude() + "\n经度：" + aMapLocation.getLongitude() + "\n精准度：" + aMapLocation.getAccuracy() + "\nAOI信息：" + aMapLocation.getAoiName() + "\n楼层：" + aMapLocation.getFloor();

                location_latitude=aMapLocation.getLatitude();
                location_longitude=aMapLocation.getLongitude();

                if(location_latitude<34.812249 && location_latitude>34.811818)
                {
                    if(location_longitude>113.537203 && location_longitude<113.538577)
                    {
                        tlt=tlt+ "\n您正处于机器人实验室！";
                        locationFlag=true;
                    }
                    else{
                        tlt=tlt+ "\n您不在机器人实验室范围内，请到实验室内签到！";
                        locationFlag=false;
                    }
                }
                else{
                    locationFlag=false;
                }
                locinfo.setText(tlt);
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Toast.makeText(this,errText,Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            mLocationOption.setInterval(1000);
            mLocationOption.setNeedAddress(true);
            mLocationOption.setMockEnable(false);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}
